package org.demo.base.config;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Component;

/**
 * ReqestFilter 记录请求
 * 
 */
@Component
@WebFilter(urlPatterns = { "/api/**" })
public class ReqestFilter implements Filter {
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException {
		HttpServletRequest req = (HttpServletRequest) request;
		String title = "Filter:" + req.getRequestURI() + " staffName:" + req.getHeader(HcConstants.ReqHeader.STAFFNAME);
		try {
			LogUtil.info(ReqestFilter.class, title, System.getProperty("line.separator"));
			chain.doFilter(request, response);
		} catch (Exception e) {
			LogUtil.error(ReqestFilter.class, title, System.getProperty("line.separator"), e);
			PrintWriter out = response.getWriter();
			out.print("code:2, message: " + e.getMessage());
			out.close();
		}
	}

	@Override
	public void destroy() {

	}

}
